home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 301-325 / disk_313 / uucp / uucp1.lzh / src / compress / compress.c next >
C/C++ Source or Header  |  1989-11-03  |  41KB  |  1,571 lines

  1.  
  2. /*
  3.  * Compress - data compression program
  4.  */
  5.  
  6. #include "/version.h"
  7.  
  8. IDENT(".00");
  9.  
  10. /*
  11.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  12.  */
  13.  
  14. void Usage();
  15. void output();
  16. void writeerr();
  17. void copystat();
  18. void onintr();
  19. void cl_block();
  20. void cl_hash();
  21. void prratio();
  22. void version();
  23. void oops();
  24.  
  25.  
  26. /*
  27.  * Set USERMEM to the maximum amount of physical user memory available
  28.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  29.  * for compression.
  30.  *
  31.  * SACREDMEM is the amount of physical memory saved for others; compress
  32.  * will hog the rest.
  33.  */
  34.  
  35. #ifndef SACREDMEM
  36. #define SACREDMEM    0
  37. #endif
  38.  
  39. #ifndef USERMEM
  40. /*# ifdef AMIGA
  41. #   define USERMEM    200000
  42. # else*/
  43. #   define USERMEM    450000    /* default user memory */
  44. /* # endif*/
  45. #endif
  46.  
  47. #ifdef interdata        /* (Perkin-Elmer) */
  48. #define SIGNED_COMPARE_SLOW    /* signed compare is slower than unsigned */
  49. #endif
  50.  
  51. #ifdef pdp11
  52. # define BITS    12    /* max bits/code for 16-bit machine */
  53. # define NO_UCHAR    /* also if "unsigned char" functions as signed char */
  54. # undef USERMEM
  55. #endif /* pdp11 */    /* don't forget to compile with -i */
  56.  
  57. #ifdef z8000
  58. # define BITS    12
  59. # undef vax        /* weird preprocessor */
  60. # undef USERMEM
  61. #endif /* z8000 */
  62.  
  63. #ifdef pcxt
  64. # define BITS    12
  65. # undef USERMEM
  66. #endif /* pcxt */
  67.  
  68. #ifdef USERMEM
  69. # if USERMEM >= (433484+SACREDMEM)
  70. #  define PBITS 16
  71. # else
  72. #  if USERMEM >= (229600+SACREDMEM)
  73. #   define PBITS    15
  74. #  else
  75. #   if USERMEM >= (127536+SACREDMEM)
  76. #    define PBITS    14
  77. #   else
  78. #    if USERMEM >= (73464+SACREDMEM)
  79. #     define PBITS    13
  80. #    else
  81. #     define PBITS    12
  82. #    endif
  83. #   endif
  84. #  endif
  85. # endif
  86. # undef USERMEM
  87. #endif /* USERMEM */
  88.  
  89. #ifdef PBITS        /* Preferred BITS for this memory size */
  90. # ifndef BITS
  91. #  define BITS PBITS
  92. # endif BITS
  93. #endif /* PBITS */
  94.  
  95. #if BITS == 16
  96. # define HSIZE    69001        /* 95% occupancy */
  97. #endif
  98. #if BITS == 15
  99. # define HSIZE    35023        /* 94% occupancy */
  100. #endif
  101. #if BITS == 14
  102. # define HSIZE    18013        /* 91% occupancy */
  103. #endif
  104. #if BITS == 13
  105. # define HSIZE    9001        /* 91% occupancy */
  106. #endif
  107. #if BITS <= 12
  108. # define HSIZE    5003        /* 80% occupancy */
  109. #endif
  110.  
  111. #ifdef M_XENIX            /* Stupid compiler can't handle arrays with */
  112. # if BITS == 16         /* more than 65535 bytes - so we fake it */
  113. #  define XENIX_16
  114. # else
  115. #  if BITS > 13         /* Code only handles BITS = 12, 13, or 16 */
  116. #   define BITS 13
  117. #  endif
  118. # endif
  119. #endif
  120.  
  121. /*
  122.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  123.  */
  124. #if BITS > 15
  125. typedef long int    code_int;
  126. #else
  127. typedef int        code_int;
  128. #endif
  129.  
  130. #ifdef SIGNED_COMPARE_SLOW
  131. typedef unsigned long int count_int;
  132. typedef unsigned short int count_short;
  133. #else
  134. typedef long int      count_int;
  135. #endif
  136.  
  137. #ifdef NO_UCHAR
  138.  typedef char    char_type;
  139. #else
  140.  typedef    unsigned char    char_type;
  141. #endif /* UCHAR */
  142. char_type magic_header[] = { "\037\235" };      /* 1F 9D */
  143.  
  144. /* Defines for third byte of header */
  145. #define BIT_MASK    0x1f
  146. #define BLOCK_MASK    0x80
  147. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  148.    a fourth header byte (for expansion).
  149. */
  150. #define INIT_BITS 9            /* initial number of bits/code */
  151.  
  152. /*
  153.  * compress.c - File compression ala IEEE Computer, June 1984.
  154.  *
  155.  * Authors:    Spencer W. Thomas    (decvax!harpo!utah-cs!utah-gr!thomas)
  156.  *        Jim McKie        (decvax!mcvax!jim)
  157.  *        Steve Davies        (decvax!vax135!petsd!peora!srd)
  158.  *        Ken Turkowski        (decvax!decwrl!turtlevax!ken)
  159.  *        James A. Woods        (decvax!ihnp4!ames!jaw)
  160.  *        Joe Orost        (decvax!vax135!petsd!joe)
  161.  *
  162.  * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  163.  * $Log:    compress.c,v $
  164.  * Revision 4.0  85/07/30  12:50:00  joe
  165.  * Removed ferror() calls in output routine on every output except first.
  166.  * Prepared for release to the world.
  167.  *
  168.  * Revision 3.6  85/07/04  01:22:21  joe
  169.  * Remove much wasted storage by overlaying hash table with the tables
  170.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  171.  * computations.  Fixed dump_tab() DEBUG routine.
  172.  *
  173.  * Revision 3.5  85/06/30  20:47:21  jaw
  174.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  175.  * speedups render the megamemory version defunct, for now.  Make decoder
  176.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  177.  *
  178.  * Revision 3.4  85/06/27  12:00:00  ken
  179.  * Get rid of all floating-point calculations by doing all compression ratio
  180.  * calculations in fixed point.
  181.  *
  182.  * Revision 3.3  85/06/24  21:53:24  joe
  183.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  184.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  185.  *
  186.  * Revision 3.2  85/06/06  21:53:24  jaw
  187.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  188.  * Default to "quiet" output (no compression statistics).
  189.  *
  190.  * Revision 3.1  85/05/12  18:56:13  jaw
  191.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  192.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  193.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase
  194.  * output byte count by magic number size.
  195.  *
  196.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  197.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  198.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  199.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  200.  *
  201.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  202.  * Cache common hash codes based on input statistics; this improves
  203.  * performance for low-density raster images.  Pass on #ifdef bundle
  204.  * from Turkowski.
  205.  *
  206.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  207.  * Vary size of hash tables to reduce time for small files.
  208.  * Tune PDP-11 hash function.
  209.  *
  210.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  211.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  212.  * double hashing, discussed within.  Make block compression standard.
  213.  *
  214.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  215.  * Introduce adaptive reset for block compression, to boost the rate
  216.  * another several percent.  (See mailing list notes.)
  217.  *
  218.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  219.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  220.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  221.  *
  222.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  223.  * Fold in news changes, small machine typedef from thomas,
  224.  * #ifdef interdata from joe.
  225.  *
  226.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  227.  * Configured fast table lookup for 32-bit machines.
  228.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  229.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  230.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  231.  *
  232.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  233.  * Add check for foreground before prompting user.  Insert maxbits into
  234.  * compressed file.  Force file being uncompressed to end with ".Z".
  235.  * Added "-c" flag and "zcat".  Prepared for release.
  236.  *
  237.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  238.  * Will only compress regular files (no directories), added a magic number
  239.  * header (plus an undocumented -n flag to handle old files without headers),
  240.  * added -f flag to force overwriting of possibly existing destination file,
  241.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  242.  * filename if it doesn't have one when decompressing.  Will only replace
  243.  * file if it was compressed.
  244.  *
  245.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  246.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  247.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  248.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  249.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  250.  * 1.8.
  251.  *
  252.  * Revision 1.8  84/08/09  23:15:00  joe
  253.  * Made it compatible with vax version, installed jim's fixes/enhancements
  254.  *
  255.  * Revision 1.6  84/08/01  22:08:00  joe
  256.  * Sped up algorithm significantly by sorting the compress chain.
  257.  *
  258.  * Revision 1.5  84/07/13  13:11:00  srd
  259.  * Added C version of vax asm routines.  Changed structure to arrays to
  260.  * save much memory.  Do unsigned compares where possible (faster on
  261.  * Perkin-Elmer)
  262.  *
  263.  * Revision 1.4  84/07/05  03:11:11  thomas
  264.  * Clean up the code a little and lint it.  (Lint complains about all
  265.  * the regs used in the asm, but I'm not going to "fix" this.)
  266.  *
  267.  * Revision 1.3  84/07/05  02:06:54  thomas
  268.  * Minor fixes.
  269.  *
  270.  * Revision 1.2  84/07/05  00:27:27  thomas
  271.  * Add variable bit length output.
  272.  *
  273.  */
  274.  
  275. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  276.  
  277. #include <stdio.h>
  278. #include <ctype.h>
  279. #ifdef unix
  280. #include <signal.h>
  281. #include <sys/types.h>
  282. #include <sys/stat.h>
  283. #endif
  284.  
  285. #ifndef min
  286. #define min(a,b)        ((a>b) ? b : a)
  287. #endif
  288.  
  289. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  290.  
  291. int n_bits;                /* number of bits/code */
  292. int maxbits = BITS;            /* user settable max # bits/code */
  293. code_int maxcode;            /* maximum code, given n_bits */
  294. code_int maxmaxcode = 1 << BITS;    /* should NEVER generate this code */
  295. #ifdef COMPATIBLE        /* But wrong! */
  296. # define MAXCODE(n_bits)        (1 << (n_bits) - 1)
  297. #else
  298. # define MAXCODE(n_bits)        ((1 << (n_bits)) - 1)
  299. #endif /* COMPATIBLE */
  300.  
  301. #ifdef XENIX_16
  302. count_int htab0[8192];
  303. count_int htab1[8192];
  304. count_int htab2[8192];
  305. count_int htab3[8192];
  306. count_int htab4[8192];
  307. count_int htab5[8192];
  308. count_int htab6[8192];
  309. count_int htab7[8192];
  310. count_int htab8[HSIZE-65536];
  311. count_int * htab[9] = {
  312.     htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  313.  
  314. #define htabof(i)       (htab[(i) >> 13][(i) & 0x1fff])
  315. unsigned short code0tab[16384];
  316. unsigned short code1tab[16384];
  317. unsigned short code2tab[16384];
  318. unsigned short code3tab[16384];
  319. unsigned short code4tab[16384];
  320. unsigned short * codetab[5] = {
  321.     code0tab, code1tab, code2tab, code3tab, code4tab };
  322.  
  323. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  324.  
  325. #else    /* Normal machine */
  326. count_int htab [HSIZE];
  327. unsigned short codetab [HSIZE];
  328. #define htabof(i)       htab[i]
  329. #define codetabof(i)    codetab[i]
  330. #endif    /* XENIX_16 */
  331. code_int hsize = HSIZE;         /* for dynamic table sizing */
  332. count_int fsize;
  333.  
  334. /*
  335.  * To save much memory, we overlay the table used by compress() with those
  336.  * used by decompress().  The tab_prefix table is the same size and type
  337.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  338.  * get this from the beginning of htab.  The output stack uses the rest
  339.  * of htab, and contains characters.  There is plenty of room for any
  340.  * possible stack (stack used to be 8000 characters).
  341.  */
  342.  
  343. #define tab_prefixof(i) codetabof(i)
  344. #ifdef XENIX_16
  345. # define tab_suffixof(i)        ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  346. # define de_stack        ((char_type *)(htab2))
  347. #else    /* Normal machine */
  348. # define tab_suffixof(i)        ((char_type *)(htab))[i]
  349. # define de_stack        ((char_type *)&tab_suffixof(1<<BITS))
  350. #endif    /* XENIX_16 */
  351.  
  352. code_int free_ent = 0;            /* first unused entry */
  353. int exit_stat = 0;
  354.  
  355. code_int getcode();
  356.  
  357. void
  358. Usage() {
  359. #ifdef DEBUG
  360. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  361. }
  362. int debug = 0;
  363. #else
  364. fprintf(stderr,"Usage: compress [-dfvcV] [-b maxbits] [file ...]\n");
  365. }
  366. #endif /* DEBUG */
  367. int nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  368. int zcat_flg = 0;    /* Write output on stdout, suppress messages */
  369. int quiet = 1;        /* don't tell me about compression */
  370.  
  371. /*
  372.  * block compression parameters -- after all codes are used up,
  373.  * and compression rate changes, start over.
  374.  */
  375. int block_compress = BLOCK_MASK;
  376. int clear_flg = 0;
  377. long int ratio = 0;
  378. #define CHECK_GAP 10000 /* ratio check interval */
  379. count_int checkpoint = CHECK_GAP;
  380. /*
  381.  * the next two codes should not be changed lightly, as they must not
  382.  * lie within the contiguous general code space.
  383.  */
  384. #define FIRST    257    /* first free entry */
  385. #define CLEAR    256    /* table clear output code */
  386.  
  387. int force = 0;
  388. char ofname [100];
  389. #ifdef DEBUG
  390. int verbose = 0;
  391. #endif /* DEBUG */
  392. int (*bgnd_flag)();
  393.  
  394. int do_decomp = 0;
  395.  
  396. static void decompress ();
  397. static void compress ();
  398.  
  399. /*****************************************************************
  400.  * TAG( main )
  401.  *
  402.  * Algorithm from "A Technique for High Performance Data Compression",
  403.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  404.  *
  405.  * Usage: compress [-dfvc] [-b bits] [file ...]
  406.  * Inputs:
  407.  *    -d:        If given, decompression is done instead.
  408.  *
  409.  *    -c:        Write output on stdout, don't remove original.
  410.  *
  411.  *    -b:        Parameter limits the max number of bits/code.
  412.  *
  413.  *    -f:        Forces output file to be generated, even if one already
  414.  *            exists, and even if no space is saved by compressing.
  415.  *            If -f is not used, the user will be prompted if stdin is
  416.  *            a tty, otherwise, the output file will not be overwritten.
  417.  *
  418.  *    -v:        Write compression statistics
  419.  *
  420.  *    file ...:   Files to be compressed.  If none specified, stdin
  421.  *            is used.
  422.  * Outputs:
  423.  *    file.Z:     Compressed form of file with same mode, owner, and utimes
  424.  *    or stdout   (if stdin used as input)
  425.  *
  426.  * Assumptions:
  427.  *    When filenames are given, replaces with the compressed version
  428.  *    (.Z suffix) only if the file decreases in size.
  429.  * Algorithm:
  430.  *    Modified Lempel-Ziv method (LZW).  Basically finds common
  431.  * substrings and replaces them with a variable size code.  This is
  432.  * deterministic, and can be done on the fly.  Thus, the decompression
  433.  * procedure needs no input table, but tracks the way the table was built.
  434.  */
  435.  
  436.  
  437. void
  438. main( argc, argv )
  439. register int argc; char **argv;
  440. {
  441.     int overwrite = 0;    /* Do not overwrite unless given -f flag */
  442.     char tempname[100];
  443.     char **filelist, **fileptr;
  444.     char *cp, *rindex(), *malloc();
  445.  
  446. #ifdef unix
  447.     if ( (bgnd_flag = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  448.     signal ( SIGINT, onintr );
  449.     signal ( SIGSEGV, oops );
  450.     }
  451. #endif
  452.  
  453. #ifdef COMPATIBLE
  454.     nomagic = 1;    /* Original didn't have a magic number */
  455. #endif /* COMPATIBLE */
  456.  
  457.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  458.     *filelist = NULL;
  459.  
  460.     if((cp = rindex(argv[0], '/')) != 0) {
  461.     cp++;
  462.     } else {
  463.     cp = argv[0];
  464.     }
  465.     if(strcmp(cp, "uncompress") == 0) {
  466.     do_decomp = 1;
  467.     } else if(strcmp(cp, "zcat") == 0) {
  468.     do_decomp = 1;
  469.     zcat_flg = 1;
  470.     }
  471.  
  472. #ifdef BSD4_2
  473.     /* 4.2BSD dependent - take it out if not */
  474.     setlinebuf( stderr );
  475. #endif /* BSD4_2 */
  476.  
  477.     /* Argument Processing
  478.      * All flags are optional.
  479.      * -D => debug
  480.      * -V => print Version; debug verbose
  481.      * -d => do_decomp
  482.      * -v => unquiet
  483.      * -f => force overwrite of output file
  484.      * -n => no header: useful to uncompress old files
  485.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  486.      *        given also.
  487.      * -c => cat all output to stdout
  488.      * -C => generate output compatible with compress 2.0.
  489.      * if a string is left, must be an input filename.
  490.      */
  491.     for (argc--, argv++; argc > 0; argc--, argv++) {
  492.     if (**argv == '-') {    /* A flag argument */
  493.         while (*++(*argv)) {        /* Process all flags in this arg */
  494.         switch (**argv) {
  495. #ifdef DEBUG
  496.             case 'D':
  497.             debug = 1;
  498.             break;
  499.             case 'V':
  500.             verbose = 1;
  501.             version();
  502.             break;
  503. #else
  504.             case 'V':
  505.             version();
  506.             break;
  507. #endif /* DEBUG */
  508.             case 'v':
  509.             quiet = 0;
  510.             break;
  511.             case 'd':
  512.             do_decomp = 1;
  513.             break;
  514.             case 'f':
  515.             case 'F':
  516.             overwrite = 1;
  517.             force = 1;
  518.             break;
  519.             case 'n':
  520.             nomagic = 1;
  521.             break;
  522.             case 'C':
  523.             block_compress = 0;
  524.             break;
  525.             case 'b':
  526.             if (!ARGVAL()) {
  527.                 fprintf(stderr, "Missing maxbits\n");
  528.                 Usage();
  529.                 exit(1);
  530.             }
  531.             maxbits = atoi(*argv);
  532.             goto nextarg;
  533.             case 'c':
  534.             zcat_flg = 1;
  535.             break;
  536.             case 'q':
  537.             quiet = 1;
  538.             break;
  539.             default:
  540.             fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  541.             Usage();
  542.             exit(1);
  543.         }
  544.         }
  545.     }
  546.     else {        /* Input file name */
  547.         *fileptr++ = *argv; /* Build input file list */
  548.         *fileptr = NULL;
  549.         /* process nextarg; */
  550.     }
  551.     nextarg: continue;
  552.     }
  553.  
  554.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  555.     if (maxbits > BITS) maxbits = BITS;
  556.     maxmaxcode = 1 << maxbits;
  557.  
  558.     if (*filelist != NULL) {
  559.     for (fileptr = filelist; *fileptr; fileptr++) {
  560.         exit_stat = 0;
  561.         if (do_decomp != 0) {                       /* DECOMPRESSION */
  562.         /* Check for .Z suffix */
  563.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  564.             /* No .Z: tack one on */
  565.             strcpy(tempname, *fileptr);
  566.             strcat(tempname, ".Z");
  567.             *fileptr = tempname;
  568.         }
  569.         /* Open input file */
  570.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  571.             perror(*fileptr); continue;
  572.         }
  573.         /* Check the magic number */
  574.         if (nomagic == 0) {
  575.             if ((getchar() != (magic_header[0] & 0xFF))
  576.              || (getchar() != (magic_header[1] & 0xFF))) {
  577.             fprintf(stderr, "%s: not in compressed format\n",
  578.                 *fileptr);
  579.             continue;
  580.             }
  581.             maxbits = getchar();        /* set -b from file */
  582.             block_compress = maxbits & BLOCK_MASK;
  583.             maxbits &= BIT_MASK;
  584.             maxmaxcode = 1 << maxbits;
  585.             if(maxbits > BITS) {
  586.             fprintf(stderr,
  587.             "%s: compressed with %d bits, can only handle %d bits\n",
  588.             *fileptr, maxbits, BITS);
  589.             continue;
  590.             }
  591.         }
  592.         /* Generate output filename */
  593.         strcpy(ofname, *fileptr);
  594.         ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  595.         } else {                    /* COMPRESSION */
  596.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  597.             fprintf(stderr, "%s: already has .Z suffix -- no change\n",
  598.                 *fileptr);
  599.             continue;
  600.         }
  601.         /* Open input file */
  602.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  603.             perror(*fileptr); continue;
  604.         }
  605.         fsize = getfilesize (*fileptr);
  606.         /*
  607.          * tune hash table size for small files -- ad hoc,
  608.          * but the sizes match earlier #defines, which
  609.          * serve as upper bounds on the number of output codes.
  610.          */
  611.         hsize = HSIZE;
  612.         if ( fsize < (1 << 12) )
  613.             hsize = min ( 5003, HSIZE );
  614.         else if ( fsize < (1 << 13) )
  615.             hsize = min ( 9001, HSIZE );
  616.         else if ( fsize < (1 << 14) )
  617.             hsize = min ( 18013, HSIZE );
  618.         else if ( fsize < (1 << 15) )
  619.             hsize = min ( 35023, HSIZE );
  620.         else if ( fsize < 47000 )
  621.             hsize = min ( 50021, HSIZE );
  622.  
  623.         /* Generate output filename */
  624.         strcpy(ofname, *fileptr);
  625. #ifndef BSD4_2        /* Short filenames */
  626.         if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  627.         else                    cp = ofname;
  628.         if (strlen(cp) > 12) {
  629.             fprintf(stderr,"%s: filename too long to tack on .Z\n",cp);
  630.             continue;
  631.         }
  632. #endif    /* BSD4_2        Long filenames allowed */
  633.         strcat(ofname, ".Z");
  634.         }
  635.         /* Check for overwrite of existing file */
  636. #ifdef unix
  637.         if (overwrite == 0 && zcat_flg == 0) {
  638.         if (stat(ofname, &statbuf) == 0) {
  639.             char response[2];
  640.             response[0] = 'n';
  641.             fprintf(stderr, "%s already exists;", ofname);
  642.             if (foreground()) {
  643.             fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  644.             ofname);
  645.             fflush(stderr);
  646.             read(2, response, 2);
  647.             while (response[1] != '\n') {
  648.                 if (read(2, response+1, 1) < 0) {   /* Ack! */
  649.                 perror("stderr"); break;
  650.                 }
  651.             }
  652.             }
  653.             if (response[0] != 'y') {
  654.             fprintf(stderr, "\tnot overwritten\n");
  655.             continue;
  656.             }
  657.         }
  658.         }
  659. #endif
  660.         if(zcat_flg == 0) {         /* Open output file */
  661.         if (freopen(ofname, "w", stdout) == NULL) {
  662.             perror(ofname);
  663.             continue;
  664.         }
  665.         if(!quiet)
  666.             fprintf(stderr, "%s: ", *fileptr);
  667.         }
  668.  
  669.         /* Actually do the compression/decompression */
  670.         if (do_decomp == 0) compress();
  671. #ifndef DEBUG
  672.         else            decompress();
  673. #else
  674.         else if (debug == 0)        decompress();
  675.         else            printcodes();
  676.         if (verbose)                dump_tab();
  677. #endif /* DEBUG */
  678.         if(zcat_flg == 0) {
  679.         copystat(*fileptr, ofname);     /* Copy stats */
  680.         if((exit_stat == 1) || (!quiet))
  681.             putc('\n', stderr);
  682.         }
  683.     }
  684.     } else {        /* Standard input */
  685.     if (do_decomp == 0) {
  686.         compress();
  687. #ifdef DEBUG
  688.         if(verbose)             dump_tab();
  689. #endif /* DEBUG */
  690.         if(!quiet)
  691.             putc('\n', stderr);
  692.     } else {
  693.         /* Check the magic number */
  694.         if (nomagic == 0) {
  695.         if ((getchar()!=(magic_header[0] & 0xFF))
  696.          || (getchar()!=(magic_header[1] & 0xFF))) {
  697.             fprintf(stderr, "stdin: not in compressed format\n");
  698.             exit(1);
  699.         }
  700.         maxbits = getchar();    /* set -b from file */
  701.         block_compress = maxbits & BLOCK_MASK;
  702.         maxbits &= BIT_MASK;
  703.         maxmaxcode = 1 << maxbits;
  704.         fsize = 100000;     /* assume stdin large for USERMEM */
  705.         if(maxbits > BITS) {
  706.             fprintf(stderr,
  707.             "stdin: compressed with %d bits, can only handle %d bits\n",
  708.             maxbits, BITS);
  709.             exit(1);
  710.         }
  711.         }
  712. #ifndef DEBUG
  713.         decompress();
  714. #else
  715.         if (debug == 0)     decompress();
  716.         else        printcodes();
  717.         if (verbose)        dump_tab();
  718. #endif /* DEBUG */
  719.     }
  720.     }
  721.     exit(exit_stat);
  722. }
  723.  
  724. static int offset;
  725. long int in_count = 1;            /* length of input */
  726. long int bytes_out;            /* length of compressed output */
  727. long int out_count = 0;         /* # of codes output (for debugging) */
  728.  
  729. /*
  730.  * compress stdin to stdout
  731.  *
  732.  * Algorithm:  use open addressing double hashing (no chaining) on the
  733.  * prefix code / next character combination.  We do a variant of Knuth's
  734.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  735.  * secondary probe.  Here, the modular division first probe is gives way
  736.  * to a faster exclusive-or manipulation.  Also do block compression with
  737.  * an adaptive reset, whereby the code table is cleared when the compression
  738.  * ratio decreases, but after the table fills.    The variable-length output
  739.  * codes are re-sized at this point, and a special CLEAR code is generated
  740.  * for the decompressor.  Late addition:  construct the table according to
  741.  * file size for noticeable speed improvement on small files.  Please direct
  742.  * questions about this implementation to ames!jaw.
  743.  */
  744.  
  745. static void compress() {
  746.     register long fcode;
  747.     register code_int i = 0;
  748.     register int c;
  749.     register code_int ent;
  750. #ifdef XENIX_16
  751.     register code_int disp;
  752. #else    /* Normal machine */
  753.     register int disp;
  754. #endif
  755.     register code_int hsize_reg;
  756.     register int hshift;
  757.  
  758. #ifndef COMPATIBLE
  759.     if (nomagic == 0) {
  760.     putchar(magic_header[0]); putchar(magic_header[1]);
  761.     putchar((char)(maxbits | block_compress));
  762.     if(ferror(stdout))
  763.         writeerr();
  764.     }
  765. #endif /* COMPATIBLE */
  766.  
  767.     offset = 0;
  768.     bytes_out = 3;        /* includes 3-byte header mojo */
  769.     out_count = 0;
  770.     clear_flg = 0;
  771.     ratio = 0;
  772.     in_count = 1;
  773.     checkpoint = CHECK_GAP;
  774.     maxcode = MAXCODE(n_bits = INIT_BITS);
  775.     free_ent = ((block_compress) ? FIRST : 256 );
  776.  
  777.     ent = getchar ();
  778.  
  779.     hshift = 0;
  780.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  781.     hshift++;
  782.     hshift = 8 - hshift;        /* set hash code range bound */
  783.  
  784.     hsize_reg = hsize;
  785.     cl_hash( (count_int) hsize_reg);            /* clear hash table */
  786.  
  787. #ifdef SIGNED_COMPARE_SLOW
  788.     while ( (c = getchar()) != (unsigned) EOF ) {
  789. #else
  790.     while ( (c = getchar()) != EOF ) {
  791. #endif
  792.     in_count++;
  793.     fcode = (long) (((long) c << maxbits) + ent);
  794.     i = ((c << hshift) ^ ent);      /* xor hashing */
  795.  
  796.     if ( htabof (i) == fcode ) {
  797.         ent = codetabof (i);
  798.         continue;
  799.     } else if ( (long)htabof (i) < 0 )      /* empty slot */
  800.         goto nomatch;
  801.     disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  802.     if ( i == 0 )
  803.         disp = 1;
  804. probe:
  805.     if ( (i -= disp) < 0 )
  806.         i += hsize_reg;
  807.  
  808.     if ( htabof (i) == fcode ) {
  809.         ent = codetabof (i);
  810.         continue;
  811.     }
  812.     if ( (long)htabof (i) > 0 )
  813.         goto probe;
  814. nomatch:
  815.     output ( (code_int) ent );
  816.     out_count++;
  817.     ent = c;
  818. #ifdef SIGNED_COMPARE_SLOW
  819.     if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  820. #else
  821.     if ( free_ent < maxmaxcode ) {
  822. #endif
  823.         codetabof (i) = free_ent++; /* code -> hashtable */
  824.         htabof (i) = fcode;
  825.     }
  826.     else if ( (count_int)in_count >= checkpoint && block_compress )
  827.         cl_block ();
  828.     }
  829.     /*
  830.      * Put out the final code.
  831.      */
  832.     output( (code_int)ent );
  833.     out_count++;
  834.     output( (code_int)-1 );
  835.  
  836.     /*
  837.      * Print out stats on stderr
  838.      */
  839.     if(zcat_flg == 0 && !quiet) {
  840. #ifdef DEBUG
  841.     fprintf( stderr,
  842.         "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  843.         in_count, out_count, bytes_out );
  844.     prratio( stderr, in_count, bytes_out );
  845.     fprintf( stderr, "\n");
  846.     fprintf( stderr, "\tCompression as in compact: " );
  847.     prratio( stderr, in_count-bytes_out, in_count );
  848.     fprintf( stderr, "\n");
  849.     fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  850.         free_ent - 1, n_bits );
  851. #else /* !DEBUG */
  852.     fprintf( stderr, "Compression: " );
  853.     prratio( stderr, in_count-bytes_out, in_count );
  854. #endif /* DEBUG */
  855.     }
  856.     if(bytes_out > in_count)    /* exit(2) if no savings */
  857.     exit_stat = 2;
  858.     return;
  859. }
  860.  
  861. /*****************************************************************
  862.  * TAG( output )
  863.  *
  864.  * Output the given code.
  865.  * Inputs:
  866.  *    code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  867.  *        that n_bits =< (long)wordsize - 1.
  868.  * Outputs:
  869.  *    Outputs code to the file.
  870.  * Assumptions:
  871.  *    Chars are 8 bits long.
  872.  * Algorithm:
  873.  *    Maintain a BITS character long buffer (so that 8 codes will
  874.  * fit in it exactly).    Use the VAX insv instruction to insert each
  875.  * code in turn.  When the buffer fills up empty it and start over.
  876.  */
  877.  
  878. static char buf[BITS];
  879.  
  880. #ifndef vax
  881. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  882. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  883. #endif /* vax */
  884.  
  885. void
  886. output( code )
  887. code_int  code;
  888. {
  889. #ifdef DEBUG
  890.     static int col = 0;
  891. #endif /* DEBUG */
  892.  
  893.     /*
  894.      * On the VAX, it is important to have the register declarations
  895.      * in exactly the order given, or the asm will break.
  896.      */
  897.     register int r_off = offset, bits= n_bits;
  898.     register char * bp = buf;
  899.  
  900. #ifdef DEBUG
  901.     if ( verbose )
  902.         fprintf( stderr, "%5d%c", code,
  903.             (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  904. #endif /* DEBUG */
  905.     if ( code >= 0 ) {
  906. #ifdef vax
  907.     /* VAX DEPENDENT!! Implementation on other machines is below.
  908.      *
  909.      * Translation: Insert BITS bits from the argument starting at
  910.      * offset bits from the beginning of buf.
  911.      */
  912.     0;    /* Work around for pcc -O bug with asm and if stmt */
  913.     asm( "insv      4(ap),r11,r10,(r9)" );
  914. #else /* not a vax */
  915. /*
  916.  * byte/bit numbering on the VAX is simulated by the following code
  917.  */
  918.     /*
  919.      * Get to the first byte.
  920.      */
  921.     bp += (r_off >> 3);
  922.     r_off &= 7;
  923.     /*
  924.      * Since code is always >= 8 bits, only need to mask the first
  925.      * hunk on the left.
  926.      */
  927.     *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  928.     bp++;
  929.     bits -= (8 - r_off);
  930.     code >>= 8 - r_off;
  931.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  932.     if ( bits >= 8 ) {
  933.         *bp++ = code;
  934.         code >>= 8;
  935.         bits -= 8;
  936.     }
  937.     /* Last bits. */
  938.     if(bits)
  939.         *bp = code;
  940. #endif /* vax */
  941.     offset += n_bits;
  942.     if ( offset == (n_bits << 3) ) {
  943.         bp = buf;
  944.         bits = n_bits;
  945.         bytes_out += bits;
  946.         do
  947.         putchar(*bp++);
  948.         while(--bits);
  949.         offset = 0;
  950.     }
  951.  
  952.     /*
  953.      * If the next entry is going to be too big for the code size,
  954.      * then increase it, if possible.
  955.      */
  956.     if ( free_ent > maxcode || (clear_flg > 0))
  957.     {
  958.         /*
  959.          * Write the whole buffer, because the input side won't
  960.          * discover the size increase until after it has read it.
  961.          */
  962.         if ( offset > 0 ) {
  963.         if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  964.             writeerr();
  965.         bytes_out += n_bits;
  966.         }
  967.         offset = 0;
  968.  
  969.         if ( clear_flg ) {
  970.         maxcode = MAXCODE (n_bits = INIT_BITS);
  971.         clear_flg = 0;
  972.         }
  973.         else {
  974.         n_bits++;
  975.         if ( n_bits == maxbits )
  976.             maxcode = maxmaxcode;
  977.         else
  978.             maxcode = MAXCODE(n_bits);
  979.         }
  980. #ifdef DEBUG
  981.         if ( debug ) {
  982.         fprintf( stderr, "\nChange to %d bits\n", n_bits );
  983.         col = 0;
  984.         }
  985. #endif /* DEBUG */
  986.     }
  987.     } else {
  988.     /*
  989.      * At EOF, write the rest of the buffer.
  990.      */
  991.     if ( offset > 0 )
  992.         fwrite( buf, 1, (offset + 7) / 8, stdout );
  993.     bytes_out += (offset + 7) / 8;
  994.     offset = 0;
  995.     fflush( stdout );
  996. #ifdef DEBUG
  997.     if ( verbose )
  998.         fprintf( stderr, "\n" );
  999. #endif /* DEBUG */
  1000.     if( ferror( stdout ) )
  1001.         writeerr();
  1002.     }
  1003. }
  1004.  
  1005. /*
  1006.  * Decompress stdin to stdout.    This routine adapts to the codes in the
  1007.  * file building the "string" table on-the-fly; requiring no table to
  1008.  * be stored in the compressed file.  The tables used herein are shared
  1009.  * with those of the compress() routine.  See the definitions above.
  1010.  */
  1011.  
  1012. static void decompress() {
  1013.     register char_type *stackp;
  1014.     register int finchar;
  1015.     register code_int code, oldcode, incode;
  1016.  
  1017.     /*
  1018.      * As above, initialize the first 256 entries in the table.
  1019.      */
  1020.     maxcode = MAXCODE(n_bits = INIT_BITS);
  1021.     for ( code = 255; code >= 0; code-- ) {
  1022.     tab_prefixof(code) = 0;
  1023.     tab_suffixof(code) = (char_type)code;
  1024.     }
  1025.     free_ent = ((block_compress) ? FIRST : 256 );
  1026.  
  1027.     finchar = oldcode = getcode();
  1028.     if(oldcode == -1)   /* EOF already? */
  1029.     return;         /* Get out of here */
  1030.     putchar( (char)finchar );           /* first code must be 8 bits = char */
  1031.     if(ferror(stdout))          /* Crash if can't write */
  1032.     writeerr();
  1033.     stackp = de_stack;
  1034.  
  1035.     while ( (code = getcode()) > -1 ) {
  1036.  
  1037.     if ( (code == CLEAR) && block_compress ) {
  1038.         for ( code = 255; code >= 0; code-- )
  1039.         tab_prefixof(code) = 0;
  1040.         clear_flg = 1;
  1041.         free_ent = FIRST - 1;
  1042.         if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1043.         break;
  1044.     }
  1045.     incode = code;
  1046.     /*
  1047.      * Special case for KwKwK string.
  1048.      */
  1049.     if ( code >= free_ent ) {
  1050.         *stackp++ = finchar;
  1051.         code = oldcode;
  1052.     }
  1053.  
  1054.     /*
  1055.      * Generate output characters in reverse order
  1056.      */
  1057. #ifdef SIGNED_COMPARE_SLOW
  1058.     while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1059. #else
  1060.     while ( code >= 256 ) {
  1061. #endif
  1062.         *stackp++ = tab_suffixof(code);
  1063.         code = tab_prefixof(code);
  1064.     }
  1065.     *stackp++ = finchar = tab_suffixof(code);
  1066.  
  1067.     /*
  1068.      * And put them out in forward order
  1069.      */
  1070.     do
  1071.         putchar ( *--stackp );
  1072.     while ( stackp > de_stack );
  1073.  
  1074.     /*
  1075.      * Generate the new entry.
  1076.      */
  1077.     if ( (code=free_ent) < maxmaxcode ) {
  1078.         tab_prefixof(code) = (unsigned short)oldcode;
  1079.         tab_suffixof(code) = finchar;
  1080.         free_ent = code+1;
  1081.     }
  1082.     /*
  1083.      * Remember previous code.
  1084.      */
  1085.     oldcode = incode;
  1086.     }
  1087.     fflush( stdout );
  1088.     if(ferror(stdout))
  1089.     writeerr();
  1090. }
  1091.  
  1092. /*****************************************************************
  1093.  * TAG( getcode )
  1094.  *
  1095.  * Read one code from the standard input.  If EOF, return -1.
  1096.  * Inputs:
  1097.  *    stdin
  1098.  * Outputs:
  1099.  *    code or -1 is returned.
  1100.  */
  1101.  
  1102. code_int
  1103. getcode() {
  1104.     /*
  1105.      * On the VAX, it is important to have the register declarations
  1106.      * in exactly the order given, or the asm will break.
  1107.      */
  1108.     register code_int code;
  1109.     static int offset = 0, size = 0;
  1110.     static char_type buf[BITS];
  1111.     register int r_off, bits;
  1112.     register char_type *bp = buf;
  1113.  
  1114.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1115.     /*
  1116.      * If the next entry will be too big for the current code
  1117.      * size, then we must increase the size.  This implies reading
  1118.      * a new buffer full, too.
  1119.      */
  1120.     if ( free_ent > maxcode ) {
  1121.         n_bits++;
  1122.         if ( n_bits == maxbits )
  1123.         maxcode = maxmaxcode;    /* won't get any bigger now */
  1124.         else
  1125.         maxcode = MAXCODE(n_bits);
  1126.     }
  1127.     if ( clear_flg > 0) {
  1128.         maxcode = MAXCODE (n_bits = INIT_BITS);
  1129.         clear_flg = 0;
  1130.     }
  1131.     size = fread( buf, 1, n_bits, stdin );
  1132.     if ( size <= 0 )
  1133.         return -1;            /* end of file */
  1134.     offset = 0;
  1135.     /* Round size down to integral number of codes */
  1136.     size = (size << 3) - (n_bits - 1);
  1137.     }
  1138.     r_off = offset;
  1139.     bits = n_bits;
  1140. #ifdef vax
  1141.     asm( "extzv   r10,r9,(r8),r11" );
  1142. #else /* not a vax */
  1143.     /*
  1144.      * Get to the first byte.
  1145.      */
  1146.     bp += (r_off >> 3);
  1147.     r_off &= 7;
  1148.     /* Get first part (low order bits) */
  1149. #ifdef NO_UCHAR
  1150.     code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1151. #else
  1152.     code = (*bp++ >> r_off);
  1153. #endif /* NO_UCHAR */
  1154.     bits -= (8 - r_off);
  1155.     r_off = 8 - r_off;        /* now, offset into code word */
  1156.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1157.     if ( bits >= 8 ) {
  1158. #ifdef NO_UCHAR
  1159.         code |= (*bp++ & 0xff) << r_off;
  1160. #else
  1161.         code |= *bp++ << r_off;
  1162. #endif /* NO_UCHAR */
  1163.         r_off += 8;
  1164.         bits -= 8;
  1165.     }
  1166.     /* high order bits. */
  1167.     code |= (*bp & rmask[bits]) << r_off;
  1168. #endif /* vax */
  1169.     offset += n_bits;
  1170.  
  1171.     return code;
  1172. }
  1173.  
  1174. char *
  1175. rindex(s, c)            /* For those who don't have it in libc.a */
  1176. register char *s, c;
  1177. {
  1178.     char *p;
  1179.     for (p = NULL; *s; s++)
  1180.         if (*s == c)
  1181.         p = s;
  1182.     return(p);
  1183. }
  1184.  
  1185. #ifdef DEBUG
  1186. printcodes()
  1187. {
  1188.     /*
  1189.      * Just print out codes from input file.  For debugging.
  1190.      */
  1191.     code_int code;
  1192.     int col = 0, bits;
  1193.  
  1194.     bits = n_bits = INIT_BITS;
  1195.     maxcode = MAXCODE(n_bits);
  1196.     free_ent = ((block_compress) ? FIRST : 256 );
  1197.     while ( ( code = getcode() ) >= 0 ) {
  1198.     if ( (code == CLEAR) && block_compress ) {
  1199.         free_ent = FIRST - 1;
  1200.         clear_flg = 1;
  1201.     }
  1202.     else if ( free_ent < maxmaxcode )
  1203.         free_ent++;
  1204.     if ( bits != n_bits ) {
  1205.         fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1206.         bits = n_bits;
  1207.         col = 0;
  1208.     }
  1209.     fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1210.     }
  1211.     putc( '\n', stderr );
  1212.     exit( 0 );
  1213. }
  1214.  
  1215. code_int sorttab[1<<BITS];    /* sorted pointers into htab */
  1216.  
  1217. dump_tab()      /* dump string table */
  1218. {
  1219.     register int i, first;
  1220.     register ent;
  1221. #define STACK_SIZE    15000
  1222.     int stack_top = STACK_SIZE;
  1223.     register c;
  1224.  
  1225.     if(do_decomp == 0) {        /* compressing */
  1226.     register int flag = 1;
  1227.  
  1228.     for(i=0; i<hsize; i++) {        /* build sort pointers */
  1229.         if((long)htabof(i) >= 0) {
  1230.             sorttab[codetabof(i)] = i;
  1231.         }
  1232.     }
  1233.     first = block_compress ? FIRST : 256;
  1234.     for(i = first; i < free_ent; i++) {
  1235.         fprintf(stderr, "%5d: \"", i);
  1236.         de_stack[--stack_top] = '\n';
  1237.         de_stack[--stack_top] = '"';
  1238.         stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff,
  1239.                      stack_top);
  1240.         for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1241.             ent > 256;
  1242.             ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1243.             stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1244.                         stack_top);
  1245.         }
  1246.         stack_top = in_stack(ent, stack_top);
  1247.         fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1248.         stack_top = STACK_SIZE;
  1249.     }
  1250.    } else if(!debug) {  /* decompressing */
  1251.  
  1252.        for ( i = 0; i < free_ent; i++ ) {
  1253.        ent = i;
  1254.        c = tab_suffixof(ent);
  1255.        if ( isascii(c) && isprint(c) )
  1256.            fprintf( stderr, "%5d: %5d/'%c'  \"",
  1257.                ent, tab_prefixof(ent), c );
  1258.        else
  1259.            fprintf( stderr, "%5d: %5d/\\%03o \"",
  1260.                ent, tab_prefixof(ent), c );
  1261.        de_stack[--stack_top] = '\n';
  1262.        de_stack[--stack_top] = '"';
  1263.        for ( ; ent != NULL;
  1264.            ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1265.            stack_top = in_stack(tab_suffixof(ent), stack_top);
  1266.        }
  1267.        fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1268.        stack_top = STACK_SIZE;
  1269.        }
  1270.     }
  1271. }
  1272.  
  1273. int
  1274. in_stack(c, stack_top)
  1275.     register c, stack_top;
  1276. {
  1277.     if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1278.         de_stack[--stack_top] = c;
  1279.     } else {
  1280.         switch( c ) {
  1281.         case '\n': de_stack[--stack_top] = 'n'; break;
  1282.         case '\t': de_stack[--stack_top] = 't'; break;
  1283.         case '\b': de_stack[--stack_top] = 'b'; break;
  1284.         case '\f': de_stack[--stack_top] = 'f'; break;
  1285.         case '\r': de_stack[--stack_top] = 'r'; break;
  1286.         case '\\': de_stack[--stack_top] = '\\'; break;
  1287.         default:
  1288.         de_stack[--stack_top] = '0' + c % 8;
  1289.         de_stack[--stack_top] = '0' + (c / 8) % 8;
  1290.         de_stack[--stack_top] = '0' + c / 64;
  1291.         break;
  1292.         }
  1293.         de_stack[--stack_top] = '\\';
  1294.     }
  1295.     return stack_top;
  1296. }
  1297. #endif /* DEBUG */
  1298.  
  1299. void
  1300. writeerr()
  1301. {
  1302.     perror ( ofname );
  1303.     unlink ( ofname );
  1304.     exit ( 1 );
  1305. }
  1306.  
  1307. void
  1308. copystat(ifname, ofname)
  1309. char *ifname, *ofname;
  1310. {
  1311. #ifdef unix
  1312.     struct stat statbuf;
  1313.     int mode;
  1314.     time_t timep[2];
  1315.  
  1316.     fclose(stdout);
  1317.     if (stat(ifname, &statbuf)) {               /* Get stat on input file */
  1318.     perror(ifname);
  1319.     return;
  1320.     }
  1321.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1322.     if(quiet)
  1323.         fprintf(stderr, "%s: ", ifname);
  1324.     fprintf(stderr, " -- not a regular file: unchanged");
  1325.     exit_stat = 1;
  1326.     } else if (statbuf.st_nlink > 1) {
  1327.     if(quiet)
  1328.         fprintf(stderr, "%s: ", ifname);
  1329.     fprintf(stderr, " -- has %d other links: unchanged",
  1330.         statbuf.st_nlink - 1);
  1331.     exit_stat = 1;
  1332.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1333.     if(!quiet)
  1334.         fprintf(stderr, " -- file unchanged");
  1335.     } else {            /* ***** Successful Compression ***** */
  1336.     exit_stat = 0;
  1337.     mode = statbuf.st_mode & 07777;
  1338.     if (chmod(ofname, mode))                /* Copy modes */
  1339.         perror(ofname);
  1340.     chown(ofname, statbuf.st_uid, statbuf.st_gid);  /* Copy ownership */
  1341.     timep[0] = statbuf.st_atime;
  1342.     timep[1] = statbuf.st_mtime;
  1343.     utime(ofname, timep);   /* Update last accessed and modified times */
  1344.     if (unlink(ifname))     /* Remove input file */
  1345.         perror(ifname);
  1346.     if(!quiet)
  1347.         fprintf(stderr, " -- replaced with %s", ofname);
  1348.     return;     /* Successful return */
  1349.     }
  1350.  
  1351.     /* Unsuccessful return -- one of the tests failed */
  1352.     if (unlink(ofname))
  1353.     perror(ofname);
  1354. #endif
  1355. }
  1356. /*
  1357.  * This routine returns 1 if we are running in the foreground and stderr
  1358.  * is a tty.
  1359.  */
  1360. #ifdef unix
  1361. foreground()
  1362. {
  1363.     if(bgnd_flag) { /* background? */
  1364.         return(0);
  1365.     } else {            /* foreground */
  1366.         if(isatty(2)) {         /* and stderr is a tty */
  1367.             return(1);
  1368.         } else {
  1369.             return(0);
  1370.         }
  1371.     }
  1372. }
  1373. #endif
  1374.  
  1375. void
  1376. onintr ( )
  1377. {
  1378.     unlink ( ofname );
  1379.     exit ( 1 );
  1380. }
  1381.  
  1382. void
  1383. oops ( )        /* wild pointer -- assume bad input */
  1384. {
  1385.     if ( do_decomp == 1 )
  1386.     fprintf ( stderr, "uncompress: corrupt input\n" );
  1387.     unlink ( ofname );
  1388.     exit ( 1 );
  1389. }
  1390.  
  1391. void
  1392. cl_block ()             /* table clear for block compress */
  1393. {
  1394.     register long int rat;
  1395.  
  1396.     checkpoint = in_count + CHECK_GAP;
  1397. #ifdef DEBUG
  1398.     if ( debug ) {
  1399.         fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1400.         prratio ( stderr, in_count, bytes_out );
  1401.         fprintf ( stderr, "\n");
  1402.     }
  1403. #endif /* DEBUG */
  1404.  
  1405.     if(in_count > 0x007fffff) { /* shift will overflow */
  1406.     rat = bytes_out >> 8;
  1407.     if(rat == 0) {          /* Don't divide by zero */
  1408.         rat = 0x7fffffff;
  1409.     } else {
  1410.         rat = in_count / rat;
  1411.     }
  1412.     } else {
  1413.     rat = (in_count << 8) / bytes_out;      /* 8 fractional bits */
  1414.     }
  1415.     if ( rat > ratio ) {
  1416.     ratio = rat;
  1417.     } else {
  1418.     ratio = 0;
  1419. #ifdef DEBUG
  1420.     if(verbose)
  1421.         dump_tab();     /* dump string table */
  1422. #endif
  1423.     cl_hash ( (count_int) hsize );
  1424.     free_ent = FIRST;
  1425.     clear_flg = 1;
  1426.     output ( (code_int) CLEAR );
  1427. #ifdef DEBUG
  1428.     if(debug)
  1429.         fprintf ( stderr, "clear\n" );
  1430. #endif /* DEBUG */
  1431.     }
  1432. }
  1433.  
  1434. void
  1435. cl_hash(hsize)          /* reset code table */
  1436.     register count_int hsize;
  1437. {
  1438. #ifndef XENIX_16    /* Normal machine */
  1439.     register count_int *htab_p = htab+hsize;
  1440. #else
  1441.     register j;
  1442.     register long k = hsize;
  1443.     register count_int *htab_p;
  1444. #endif
  1445.     register long i;
  1446.     register long m1 = -1;
  1447.  
  1448. #ifdef XENIX_16
  1449.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1450.     i = 8192;
  1451.     if(k < 8192) {
  1452.         i = k;
  1453.     }
  1454.     htab_p = &(htab[j][i]);
  1455.     i -= 16;
  1456.     if(i > 0) {
  1457. #else
  1458.     i = hsize - 16;
  1459. #endif
  1460.     do {                /* might use Sys V memset(3) here */
  1461.         *(htab_p-16) = m1;
  1462.         *(htab_p-15) = m1;
  1463.         *(htab_p-14) = m1;
  1464.         *(htab_p-13) = m1;
  1465.         *(htab_p-12) = m1;
  1466.         *(htab_p-11) = m1;
  1467.         *(htab_p-10) = m1;
  1468.         *(htab_p-9) = m1;
  1469.         *(htab_p-8) = m1;
  1470.         *(htab_p-7) = m1;
  1471.         *(htab_p-6) = m1;
  1472.         *(htab_p-5) = m1;
  1473.         *(htab_p-4) = m1;
  1474.         *(htab_p-3) = m1;
  1475.         *(htab_p-2) = m1;
  1476.         *(htab_p-1) = m1;
  1477.         htab_p -= 16;
  1478.     } while ((i -= 16) >= 0);
  1479. #ifdef XENIX_16
  1480.     }
  1481.     }
  1482. #endif
  1483.     for ( i += 16; i > 0; i-- )
  1484.         *--htab_p = m1;
  1485. }
  1486.  
  1487. void
  1488. prratio(stream, num, den)
  1489. FILE *stream;
  1490. long int num, den;
  1491. {
  1492.     register int q;         /* Doesn't need to be long */
  1493.  
  1494.     if(num > 214748L) {             /* 2147483647/10000 */
  1495.         q = num / (den / 10000L);
  1496.     } else {
  1497.         q = 10000L * num / den;     /* Long calculations, though */
  1498.     }
  1499.     if (q < 0) {
  1500.         putc('-', stream);
  1501.         q = -q;
  1502.     }
  1503.     fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1504. }
  1505.  
  1506. void
  1507. version()
  1508. {
  1509.     fprintf(stderr, "%s\n", rcs_ident);
  1510.     fprintf(stderr, "Options: ");
  1511. #ifdef vax
  1512.     fprintf(stderr, "vax, ");
  1513. #endif
  1514. #ifdef NO_UCHAR
  1515.     fprintf(stderr, "NO_UCHAR, ");
  1516. #endif
  1517. #ifdef SIGNED_COMPARE_SLOW
  1518.     fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1519. #endif
  1520. #ifdef XENIX_16
  1521.     fprintf(stderr, "XENIX_16, ");
  1522. #endif
  1523. #ifdef COMPATIBLE
  1524.     fprintf(stderr, "COMPATIBLE, ");
  1525. #endif
  1526. #ifdef DEBUG
  1527.     fprintf(stderr, "DEBUG, ");
  1528. #endif
  1529. #ifdef BSD4_2
  1530.     fprintf(stderr, "BSD4_2, ");
  1531. #endif
  1532.     fprintf(stderr, "BITS = %d\n", BITS);
  1533. }
  1534.  
  1535. /*
  1536.  *    Get the size of the file.  Although this is also possible on
  1537.  *    the Amiga, I have not yet implemented this as it is apparently
  1538.  *    used only to adapt the algorithm to make it more efficient for
  1539.  *    small files.  For files on the standard input, the file size
  1540.  *    is unknown, and 100000 is assumed, so we use that value here.
  1541.  *    Fred Fish  14-Jan-86
  1542.  */
  1543.  
  1544. long
  1545. getfilesize (name)
  1546. char *name;
  1547. {
  1548. #ifdef unix
  1549.     struct stat statbuf;
  1550.  
  1551.     stat ( *fileptr, &statbuf );
  1552.     return (statbuf.st_size);
  1553. #else
  1554.     return (100000);
  1555. #endif
  1556. }
  1557.  
  1558. #ifndef unix
  1559. #ifndef AMIGA
  1560. void
  1561. perror (arg)
  1562. char *arg;
  1563. {
  1564.     if (arg && *arg) {
  1565.         fprintf (stderr, "%s: ", arg);
  1566.     }
  1567.     fprintf (stderr, "<unknown error>\n");
  1568. }
  1569. #endif
  1570. #endif
  1571.